Byparr/main.py

79 lines
2.2 KiB
Python
Raw Normal View History

2024-07-24 13:57:40 +00:00
from __future__ import annotations
import asyncio
2024-09-13 18:03:38 +00:00
import logging
2024-07-24 13:57:40 +00:00
import time
import uvicorn
import uvicorn.config
2024-10-18 13:55:32 +00:00
from fastapi import FastAPI, HTTPException
2024-07-24 13:57:40 +00:00
from fastapi.responses import RedirectResponse
from src.models.requests import LinkRequest, LinkResponse
from src.utils import logger
2024-07-24 15:16:46 +00:00
from src.utils.browser import bypass_cloudflare, new_browser
2024-07-25 00:06:56 +00:00
from src.utils.consts import LOG_LEVEL
2024-07-24 13:57:40 +00:00
2024-09-13 18:03:38 +00:00
app = FastAPI(debug=LOG_LEVEL == logging.DEBUG, log_level=LOG_LEVEL)
2024-07-24 13:57:40 +00:00
@app.get("/")
def read_root():
"""Redirect to /docs."""
logger.info("Redirecting to /docs")
return RedirectResponse(url="/docs", status_code=301)
2024-10-21 13:34:07 +00:00
@app.get("/health")
async def health_check():
"""Health check endpoint."""
logger.info("Health check")
browser = await new_browser()
await browser.grant_all_permissions()
page = await browser.get("https://google.com")
await page.bring_to_front()
browser.stop()
return {"status": "ok"}
2024-07-24 13:57:40 +00:00
@app.post("/v1")
async def read_item(request: LinkRequest):
"""Handle POST requests."""
2024-07-24 15:41:41 +00:00
# request.url = "https://nowsecure.nl"
2024-07-24 13:57:40 +00:00
logger.info(f"Request: {request}")
start_time = int(time.time() * 1000)
browser = await new_browser()
2024-10-21 13:12:09 +00:00
await browser.grant_all_permissions()
2024-10-19 20:35:11 +00:00
await asyncio.sleep(1)
2024-09-13 18:48:31 +00:00
page = await browser.get(request.url)
await page.bring_to_front()
timeout = request.maxTimeout
if timeout == 0:
timeout = None
2024-10-18 13:55:32 +00:00
try:
challenged = await asyncio.wait_for(bypass_cloudflare(page), timeout=timeout)
2024-10-21 13:12:09 +00:00
except asyncio.TimeoutError as e:
2024-10-19 20:35:11 +00:00
logger.info("Timed out bypassing Cloudflare")
2024-10-27 19:13:15 +01:00
browser.stop()
2024-10-21 13:12:09 +00:00
raise HTTPException(
detail="Timed out bypassing Cloudflare", status_code=408
) from e
2024-10-18 14:27:43 +00:00
except Exception as e:
2024-10-19 20:35:11 +00:00
browser.stop()
2024-10-21 13:46:26 +00:00
raise HTTPException(detail="Couldn't bypass", status_code=500) from e
2024-09-13 18:48:31 +00:00
logger.info(f"Got webpage: {request.url}")
2024-10-18 14:27:43 +00:00
response = await LinkResponse.create(
2024-09-13 18:48:31 +00:00
page=page,
start_timestamp=start_time,
challenged=challenged,
)
browser.stop()
2024-07-24 13:57:40 +00:00
return response
if __name__ == "__main__":
2024-07-25 00:06:56 +00:00
uvicorn.run(app, host="0.0.0.0", port=8191, log_level=LOG_LEVEL) # noqa: S104