Spaces:
Running
Running
File size: 2,528 Bytes
c3f1552 eeef35e 0224158 3636bc2 4929f3f ce015b1 4929f3f 0224158 eeef35e 0224158 eeef35e c3f1552 0224158 eeef35e 0224158 c3f1552 0224158 7c1f802 3636bc2 0224158 30077f4 0224158 eeef35e 0224158 eeef35e 0224158 c3f1552 0224158 c3f1552 eeef35e 0224158 30077f4 eeef35e 0224158 eeef35e 0224158 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import json
from pathlib import Path
from urllib.parse import urlparse
app = FastAPI()
# --- CORS Configuration ---
origins = ["*"] # Allow all origins for development (restrict in production)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- File-based Storage Setup ---
STORAGE_FILE = Path("cookies.json")
def load_cookies():
if STORAGE_FILE.exists():
try:
with open(STORAGE_FILE, "r") as f:
return json.load(f)
except json.JSONDecodeError:
return {}
return {}
def save_cookies_to_file(data):
with open(STORAGE_FILE, "w") as f:
json.dump(data, f)
save_data = load_cookies()
# --- POST Endpoint: Save Cookies ---
@app.post("/save-cookies")
async def save_cookies(request: Request):
try:
data = await request.json()
print(f"Received POST data: {data}")
# Validate structure
if "raw_cookies_string" in data and "source_url" in data:
# Extract domain like 'youtube' or 'instagram' from the source_url
parsed_domain = urlparse(data["source_url"]).hostname or ""
domain_key = parsed_domain.split('.')[-2] if parsed_domain else "unknown"
# Clean and normalize key if needed
domain_key = domain_key.strip().lower()
# Save data dynamically using the domain_key
save_data[domain_key] = {
"raw_cookies": data["raw_cookies_string"],
"source_url": data["source_url"]
}
save_cookies_to_file(save_data)
print(f"Stored data: {save_data}")
return JSONResponse(content={"message": "Cookies received and stored"}, status_code=200)
else:
return JSONResponse(content={"message": "Invalid data structure"}, status_code=400)
except Exception as e:
print(f"Error in POST: {e}")
return JSONResponse(content={"message": f"Error: {e}"}, status_code=500)
# --- GET Endpoint: Retrieve Cookies ---
@app.get("/cookies")
async def get_cookies():
print(f"Returning stored cookies: {save_data}")
return JSONResponse(content=save_data, status_code=200)
# --- Root Endpoint: Status Check ---
@app.get("/")
async def read_root():
return {"message": "Cookie Receiver API is running!"}
|