Byparr/main.py

59 lines
1.6 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)
@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-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)
except asyncio.TimeoutError as e:
await page.save_screenshot("errors/error.png")
raise HTTPException(detail="Timeout", status_code=408) from e
2024-09-13 18:48:31 +00:00
logger.info(f"Got webpage: {request.url}")
2024-10-18 13:55:32 +00:00
response = 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