from fastapi import FastAPI, HTTPException import requests import re import os import random from urllib.parse import urlparse app = FastAPI() USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0" ] def get_random_ip(): return f"{random.randint(1, 200)}.{random.randint(1, 255)}.{random.randint(1, 255)}.{random.randint(1, 255)}" def get_buzz_info(buzz_url): session = requests.Session() current_ua = random.choice(USER_AGENTS) fake_ip = get_random_ip() # Common headers base_headers = { "User-Agent": current_ua, "Accept-Language": "en-US,en;q=0.5", "X-Forwarded-For": fake_ip, "X-Real-IP": fake_ip } try: # --- Step 1: Visit Page --- r = session.get(buzz_url, headers=base_headers, timeout=10) r.raise_for_status() # Robust Filename Extraction filename = "buzzheavier_file" name_match = re.search(r'([^<]+)', r.text) if name_match: filename = name_match.group(1).strip() # --- Step 2: Trigger HTMX Download --- dl_url = buzz_url.rstrip("/") + "/download" dl_headers = base_headers.copy() dl_headers.update({ "Accept": "*/*", "HX-Request": "true", "HX-Current-URL": buzz_url, "Referer": buzz_url, "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", }) # Allow redirects=False to catch the 302 location r2 = session.get(dl_url, headers=dl_headers, timeout=10, allow_redirects=False) # Logic: Either 302 Redirect OR JSON response with location download_link = None if r2.status_code in [301, 302, 303, 307, 308]: download_link = r2.headers.get("Location") elif "hx-redirect" in r2.headers: download_link = r2.headers.get("hx-redirect") if not download_link: raise ValueError(f"Could not resolve link. Status: {r2.status_code}") # Cookies cookie_string = "; ".join([f"{k}={v}" for k, v in session.cookies.get_dict().items()]) return { "filename": filename, "download_url": download_link, "cookies": cookie_string, "user_agent": current_ua } except Exception as e: print(f"Resolver Error: {e}") return None @app.get("/") def home(): return {"status": "Buzz Resolver Active"} @app.get("/resolve") def resolve_url(url: str): if not url: raise HTTPException(status_code=400, detail="Missing URL") data = get_buzz_info(url) if not data: raise HTTPException(status_code=500, detail="Resolution failed") return data