2024-04-13 23:53:50 +00:00
|
|
|
import re
|
|
|
|
import requests
|
2024-04-13 22:41:22 +00:00
|
|
|
from fastapi import FastAPI
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from typing import Optional
|
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
|
|
|
SHORTEN_DOMAINS = [
|
|
|
|
't.co'
|
|
|
|
]
|
|
|
|
|
|
|
|
app = FastAPI(docs_url=None, redoc_url=None)
|
|
|
|
|
|
|
|
app.add_middleware(
|
|
|
|
CORSMiddleware,
|
|
|
|
allow_origins=["*"],
|
2024-04-13 23:40:20 +00:00
|
|
|
allow_credentials=False,
|
|
|
|
allow_methods=["GET"],
|
|
|
|
allow_headers=["*"]
|
2024-04-13 22:41:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-04-13 23:53:50 +00:00
|
|
|
def unshorten_url(url: str):
|
|
|
|
pattern = re.compile(r"<title>(.*?)<\/title>")
|
|
|
|
|
|
|
|
response = requests.get(
|
|
|
|
url=url,
|
|
|
|
headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0"}
|
|
|
|
)
|
|
|
|
|
|
|
|
match = pattern.search(response.text)
|
|
|
|
if match:
|
|
|
|
return match.group(1)
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2024-04-13 22:41:22 +00:00
|
|
|
@app.get('/')
|
2024-04-13 23:41:10 +00:00
|
|
|
async def receive_url(url: Optional[str] = None):
|
2024-04-13 22:41:22 +00:00
|
|
|
if url is None:
|
|
|
|
return {"error": "no url provided"}
|
|
|
|
|
|
|
|
domain = urlparse(url).netloc
|
|
|
|
|
2024-04-13 23:53:50 +00:00
|
|
|
if domain not in SHORTEN_DOMAINS:
|
2024-04-13 22:41:22 +00:00
|
|
|
return {"error": f"cannot shorten {url}"}
|
2024-04-13 23:53:50 +00:00
|
|
|
|
|
|
|
unshortened = unshorten_url(url)
|
|
|
|
|
|
|
|
return {"result": unshortened}
|