Spaces:
Sleeping
Sleeping
Upload main.py
Browse files123456765 unmodified lines737475767778796 unmodified lines86878889909192914 unmodified lines1007100810091010101110121013162 unmodified lines1176117711781179import socketsocket.setdefaulttimeout(4000)from fastapi import FastAPI, HTTPExceptionfrom 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")# --- 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?}# --- Google Sheets Initialization ---sheets_service = None # Initialize as None914 unmodified lineslogger.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.")asyncio.create_task(update_cache_periodically())# --- API Endpoints ---162 unmodified linesreturn status_detail# If we reach here, status is 'ok'return status_detail123456765 unmodified lines73747576777879808182836 unmodified lines909192939495969798914 unmodified lines1013101410151016101710181019102010211022162 unmodified lines11851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366import socketsocket.setdefaulttimeout(4000)from 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?"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 lineslogger.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 linesreturn status_detail# If we reach here, status is 'ok'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 originpath: str # URL path visitedip_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 timecurrent_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 emojiflag_emoji = "๐" # Default globe emojiif 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 entryvisitor_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 queuecache["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 immediatelyshould_send_now = len(cache["visitors"]) >= MAX_VISITORS_PER_WEBHOOKif 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_SECONDSelse:# First visitor, send after accumulating more or after intervalshould_send_now = False# Send webhook if neededif 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 Falsetry:current_time = datetime.now()# Group visitors by device type for better organizationvisitors_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 groupfields = []for device_key, visitors in visitors_by_device.items():visits_text = ""for v in visitors:# Format the path more specifically as shown in the examplepath_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 AMtimestamp_str = v['timestamp'].strftime("%A, %B %d, %Y %I:%M %p")# Format similar to the example in the screenshotvisits_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 wordingembed = {"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 notificationasync 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 timestampcache["visitors"] = []cache["last_visitor_webhook"] = current_timereturn Trueexcept 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 passedif 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 checkawait asyncio.sleep(60) # Check every minuteexcept Exception as e:logger.error(f"Error in visitor webhook background task: {e}")await asyncio.sleep(60) # Wait and retry
main.py+190-3