Spaces:
Sleeping
Sleeping
Upload main.py
Browse files1234456765 unmodified lines73747576777879808182836 unmodified lines90919289939495969798914 unmodified lines1013101410151016101710181019102010211022162 unmodified lines118511861187117911881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366import socketsocket.setdefaulttimeout(4000)
from fastapi import FastAPI, HTTPExceptionfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optional, Any, Dict, List65 unmodified linesSCAMMER_WEBHOOK_URL = os.getenv("SCAMMER_WEBHOOK_URL")VALUE_WEBHOOK_URL = os.getenv("VALUE_WEBHOOK_URL")DUPE_CHECK_WEBHOOK_URL = os.getenv("DUPE_CHECK_WEBHOOK_URL")VISITOR_WEBHOOK_URL = os.getenv("VISITOR_WEBHOOK_URL") # New webhook URL for visitor tracking
# Visitor tracking configurationVISITOR_BATCH_INTERVAL_SECONDS = 60 # Send visitor webhooks every 1 minuteMAX_VISITORS_PER_WEBHOOK = 3 # Maximum number of visitors to include in a single webhook
# --- Global Cache ---cache = {6 unmodified lines "dupes": [], # List of duped usernames "last_updated": None, # Timestamp of the last successful/partial update "is_ready": False, # Is the cache populated at least once? "service_available": True # Is the Google Sheets service reachable? "service_available": True, # Is the Google Sheets service reachable? "visitors": [], # Recent visitors for batched webhook notifications "last_visitor_webhook": None # Timestamp of last visitor webhook}# --- Google Sheets Initialization ---sheets_service = None # Initialize as None914 unmodified lines logger.warning("VALUE_WEBHOOK_URL environment variable not set. Value change notifications disabled.") if not DUPE_CHECK_WEBHOOK_URL: logger.warning("WEBHOOK_URL (for dupe checks) environment variable not set. Dupe check notifications disabled.") if not VISITOR_WEBHOOK_URL: logger.warning("VISITOR_WEBHOOK_URL environment variable not set. Visitor tracking notifications disabled.") asyncio.create_task(update_cache_periodically()) asyncio.create_task(visitor_webhook_task()) # Start visitor webhook background task
# --- API Endpoints ---162 unmodified lines return status_detail
# If we reach here, status is 'ok' return status_detail return status_detail
# --- Visitor Tracking Model and Endpoint ---class VisitorData(BaseModel): device_type: str # "Laptop", "Desktop", "Mobile", etc. os: str # "Windows 10", "MacOS", etc. browser: str # "Chrome", "Firefox", etc. country: str # Country of origin path: str # URL path visited ip_address: Optional[str] = None # Optional IP address (for internal use only) @app.post("/api/track-visitor")async def track_visitor(visitor: VisitorData, request: Request): """Records visitor information and adds it to the visitor queue""" # Get client IP (for internal tracking, not included in webhook) client_host = request.client.host if request.client else "Unknown" # Format current time current_time = datetime.now() formatted_time = current_time.strftime("%A, %B %d, %Y %I:%M %p") short_time = current_time.strftime("%I:%M %p") # Get country flag emoji flag_emoji = "๐" # Default globe emoji if visitor.country.lower() == "france": flag_emoji = "๐ซ๐ท" elif visitor.country.lower() == "pakistan": flag_emoji = "๐ต๐ฐ" elif visitor.country.lower() == "united states" or visitor.country.lower() == "usa": flag_emoji = "๐บ๐ธ" elif visitor.country.lower() == "united kingdom" or visitor.country.lower() == "uk": flag_emoji = "๐ฌ๐ง" elif visitor.country.lower() == "canada": flag_emoji = "๐จ๐ฆ" elif visitor.country.lower() == "australia": flag_emoji = "๐ฆ๐บ" elif visitor.country.lower() == "germany": flag_emoji = "๐ฉ๐ช" elif visitor.country.lower() == "india": flag_emoji = "๐ฎ๐ณ" elif visitor.country.lower() == "japan": flag_emoji = "๐ฏ๐ต" elif visitor.country.lower() == "china": flag_emoji = "๐จ๐ณ" # Add more country flags as needed # Create visitor entry visitor_entry = { "device_type": visitor.device_type, "os": visitor.os, "browser": visitor.browser, "country": visitor.country, "flag_emoji": flag_emoji, "path": visitor.path, "timestamp": current_time, "formatted_time": short_time, "ip_address": client_host # Store IP internally but don't send in webhook } # Add to visitor queue cache["visitors"].append(visitor_entry) logger.info(f"Recorded visitor from {visitor.country} using {visitor.browser} visiting {visitor.path}") # Check if we should send a webhook immediately should_send_now = len(cache["visitors"]) >= MAX_VISITORS_PER_WEBHOOK if cache["last_visitor_webhook"]: time_since_last = (current_time - cache["last_visitor_webhook"]).total_seconds() should_send_now = should_send_now or time_since_last >= VISITOR_BATCH_INTERVAL_SECONDS else: # First visitor, send after accumulating more or after interval should_send_now = False # Send webhook if needed if should_send_now and VISITOR_WEBHOOK_URL: await send_visitor_webhook() return {"status": "recorded", "webhook_queued": True}
async def send_visitor_webhook(): """Sends a webhook with accumulated visitor information""" if not cache["visitors"] or not VISITOR_WEBHOOK_URL: return False try: current_time = datetime.now() # Group visitors by device type for better organization visitors_by_device = {} for visitor in cache["visitors"]: key = f"{visitor['device_type']} - {visitor['os']} - {visitor['browser']}" if key not in visitors_by_device: visitors_by_device[key] = [] visitors_by_device[key].append(visitor) # Create webhook fields for each device group fields = [] for device_key, visitors in visitors_by_device.items(): visits_text = "" for v in visitors: # Format the path more specifically as shown in the example path_display = v['path'] if "textures" in path_display.lower(): path_display = "www.JailbreakValueCentral.com/textures" elif "tires" in path_display.lower() or "rims" in path_display.lower(): path_display = "www.JailbreakValueCentral.net/tires" elif "calculator" in path_display.lower(): path_display = "www.JailbreakValueCentral.net/value-calculator" elif "drift" in path_display.lower() or "particles" in path_display.lower(): path_display = "www.JailbreakValueCentral.net/drift-particles" elif "furniture" in path_display.lower(): path_display = "www.JailbreakValueCentral.net/furniture" elif "spoilers" in path_display.lower(): path_display = "www.JailbreakValueCentral.net/spoilers" # Format date like: Sunday, April 13, 2025 2:06 AM timestamp_str = v['timestamp'].strftime("%A, %B %d, %Y %I:%M %p") # Format similar to the example in the screenshot visits_text += f"A User from {v['country']} {v['flag_emoji']} browsed:\n" visits_text += f"{timestamp_str}:\n" visits_text += f"{path_display}\n\n" fields.append({ "name": device_key, "value": visits_text.strip(), "inline": False }) # Create the embed with improved wording embed = { "title": "๐ Jailbreak Value Central Visitors", "description": "Check out the latest visitor activity from around the world! See what sections are trending right now.", "color": 3447003, # Blue "fields": fields, "timestamp": current_time.isoformat(), "footer": { "text": f"Sourced From JailbreakValueCentral.com โข Today at {current_time.strftime('%I:%M %p')}" }, "thumbnail": { "url": "https://jailbreakvalue.net/logo.png" # Update with your actual logo URL } } # Send the webhook notification async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as session: await send_webhook_notification(session, VISITOR_WEBHOOK_URL, embed) logger.info(f"Visitor tracking webhook sent with {len(cache['visitors'])} entries") # Clear the visitor queue and update timestamp cache["visitors"] = [] cache["last_visitor_webhook"] = current_time return True except Exception as e: logger.error(f"Error sending visitor tracking webhook: {e}") return False
# Background task to periodically send visitor webhooksasync def visitor_webhook_task(): """Periodically sends visitor webhooks if there are any pending""" while True: try: current_time = datetime.now() # Check if we have visitors and if enough time has passed if cache["visitors"] and VISITOR_WEBHOOK_URL: if not cache["last_visitor_webhook"] or \ (current_time - cache["last_visitor_webhook"]).total_seconds() >= VISITOR_BATCH_INTERVAL_SECONDS: await send_visitor_webhook() # Wait for next check await asyncio.sleep(60) # Check every minute except Exception as e: logger.error(f"Error in visitor webhook background task: {e}") await asyncio.sleep(60) # Wait and retrymain.py+190-3