221 lines
7.7 KiB
Python
221 lines
7.7 KiB
Python
from fastapi import APIRouter, HTTPException, Header, Response
|
|
from typing import Optional
|
|
from urllib.parse import unquote
|
|
from app.config import API_KEY
|
|
from app.database import get_cached_data, save_to_cache
|
|
from pydantic import BaseModel
|
|
from app.services.browser import (
|
|
visit_url_service,
|
|
screenshot_url_service,
|
|
click_selector_service,
|
|
extract_seo_service,
|
|
extract_meta_tags_service,
|
|
capture_outgoing_calls_service,
|
|
get_resulting_url_service
|
|
)
|
|
|
|
router = APIRouter()
|
|
|
|
class ClickRequest(BaseModel):
|
|
url: str
|
|
selector: str
|
|
# Default behavior: return screenshot after clicking.
|
|
returnType: Optional[str] = "screenshot"
|
|
|
|
@router.get("/")
|
|
async def visit_url(url: str, skipCache: bool = False, x_api_key: Optional[str] = Header(None)):
|
|
# Validate API key
|
|
if not x_api_key or x_api_key != API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
# Decode URL if it's encoded
|
|
decoded_url = unquote(url)
|
|
|
|
# Check cache first (unless skipCache is True)
|
|
if not skipCache:
|
|
cached_result = get_cached_data(decoded_url, "visit")
|
|
if cached_result:
|
|
return cached_result
|
|
|
|
try:
|
|
# Call the service function
|
|
result = await visit_url_service(decoded_url)
|
|
|
|
if(result["status"] == "success"):
|
|
# Save to cache (even if we skipped reading from it)
|
|
save_to_cache(decoded_url, "visit", result)
|
|
|
|
return result
|
|
except Exception as e:
|
|
print(f"Error visiting URL {decoded_url}: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/screenshot")
|
|
async def screenshot_url(url: str, fullPage: bool = True, x_api_key: Optional[str] = Header(None)):
|
|
"""Capture a screenshot of a website and return it as PNG"""
|
|
if not x_api_key or x_api_key != API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
decoded_url = unquote(url)
|
|
|
|
try:
|
|
result = await screenshot_url_service(decoded_url, fullPage)
|
|
|
|
if isinstance(result, dict) and result.get("status") == "error":
|
|
raise HTTPException(status_code=500, detail=result.get("error", "Screenshot capture failed"))
|
|
|
|
if not isinstance(result, (bytes, bytearray)):
|
|
raise HTTPException(status_code=500, detail="Unexpected screenshot response")
|
|
|
|
return Response(content=result, media_type="image/png")
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
print(f"Error taking screenshot for URL {decoded_url}: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.post("/click")
|
|
async def click_selector(payload: ClickRequest, x_api_key: Optional[str] = Header(None)):
|
|
if not x_api_key or x_api_key != API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
decoded_url = unquote(payload.url)
|
|
return_type = (payload.returnType or "screenshot").lower()
|
|
if return_type not in ("screenshot", "html"):
|
|
raise HTTPException(status_code=400, detail="Invalid returnType. Use 'screenshot' or 'html'.")
|
|
|
|
try:
|
|
result = await click_selector_service(decoded_url, payload.selector, return_type)
|
|
|
|
if isinstance(result, dict) and result.get("status") == "error":
|
|
raise HTTPException(status_code=500, detail=result.get("error", "Click failed"))
|
|
|
|
if return_type == "html":
|
|
if not isinstance(result, str):
|
|
raise HTTPException(status_code=500, detail="Unexpected HTML response")
|
|
return Response(content=result, media_type="text/html; charset=utf-8")
|
|
|
|
if not isinstance(result, (bytes, bytearray)):
|
|
raise HTTPException(status_code=500, detail="Unexpected screenshot response")
|
|
return Response(content=result, media_type="image/png")
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
print(f"Error clicking selector on URL {decoded_url}: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/seo")
|
|
async def extract_seo(url: str, skipCache: bool = False, x_api_key: Optional[str] = Header(None)):
|
|
"""Extract SEO information from a website"""
|
|
# Validate API key
|
|
if not x_api_key or x_api_key != API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
# Decode URL if it's encoded
|
|
decoded_url = unquote(url)
|
|
|
|
# Check cache first (unless skipCache is True)
|
|
if not skipCache:
|
|
cached_result = get_cached_data(decoded_url, "seo")
|
|
if cached_result:
|
|
return cached_result
|
|
|
|
try:
|
|
# Call the service function
|
|
result = await extract_seo_service(decoded_url)
|
|
|
|
# Save to cache
|
|
if(result["status"] == "success"):
|
|
save_to_cache(decoded_url, "seo", result)
|
|
|
|
return result
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@router.get("/meta")
|
|
async def extract_meta_tags(url: str, skipCache: bool = False, x_api_key: Optional[str] = Header(None)):
|
|
"""Extract meta tags from a website"""
|
|
# Validate API key
|
|
if not x_api_key or x_api_key != API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
# Decode URL if it's encoded
|
|
decoded_url = unquote(url)
|
|
|
|
# Check cache first (unless skipCache is True)
|
|
if not skipCache:
|
|
cached_result = get_cached_data(decoded_url, "meta")
|
|
if cached_result:
|
|
return cached_result
|
|
|
|
try:
|
|
# Call the service function
|
|
result = await extract_meta_tags_service(decoded_url)
|
|
|
|
# Save to cache
|
|
if(result["status"] == "success"):
|
|
save_to_cache(decoded_url, "meta", result)
|
|
|
|
return result
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.get("/outgoing-calls")
|
|
async def capture_outgoing_calls(url: str, skipCache: bool = False, x_api_key: Optional[str] = Header(None)):
|
|
"""Capture outgoing API calls from a website"""
|
|
# Validate API key
|
|
if not x_api_key or x_api_key != API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
# Decode URL if it's encoded
|
|
decoded_url = unquote(url)
|
|
|
|
# Check cache first (unless skipCache is True)
|
|
if not skipCache:
|
|
cached_result = get_cached_data(decoded_url, "outgoing_calls")
|
|
if cached_result:
|
|
return cached_result
|
|
|
|
try:
|
|
# Call the service function
|
|
result = await capture_outgoing_calls_service(decoded_url)
|
|
|
|
# Save to cache
|
|
if(result["status"] == "success"):
|
|
save_to_cache(decoded_url, "outgoing_calls", result)
|
|
|
|
return result
|
|
except Exception as e:
|
|
print(f"Error capturing outgoing calls for URL {decoded_url}: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.get("/resulting-url")
|
|
async def get_resulting_url(url: str, skipCache: bool = False, x_api_key: Optional[str] = Header(None)):
|
|
"""Get the resulting URL after navigation (handles redirects)"""
|
|
# Validate API key
|
|
if not x_api_key or x_api_key != API_KEY:
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
# Decode URL if it's encoded
|
|
decoded_url = unquote(url)
|
|
|
|
# Check cache first (unless skipCache is True)
|
|
if not skipCache:
|
|
cached_result = get_cached_data(decoded_url, "resulting_url")
|
|
if cached_result:
|
|
return cached_result
|
|
|
|
try:
|
|
# Call the service function
|
|
result = await get_resulting_url_service(decoded_url)
|
|
|
|
# Save to cache
|
|
if(result["status"] == "success"):
|
|
save_to_cache(decoded_url, "resulting_url", result)
|
|
|
|
return result
|
|
except Exception as e:
|
|
print(f"Error getting resulting URL for {decoded_url}: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e)) |