unshorten twitter

This commit is contained in:
agatha 2024-04-13 20:15:11 -04:00
parent 53bfc1b6e1
commit 3119af0c9f
2 changed files with 25 additions and 27 deletions

View File

@ -1,16 +1,14 @@
import re
import requests
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from typing import Optional from typing import Optional
from urllib.parse import urlparse from urllib.parse import urlparse
from unshorten import unshorten_twitter
SHORTEN_DOMAINS = [ UNSHORTENERS = {
't.co' 't.co': unshorten_twitter
] }
app = FastAPI(docs_url=None, redoc_url=None) app = FastAPI(docs_url=None, redoc_url=None)
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=["*"], allow_origins=["*"],
@ -20,21 +18,6 @@ app.add_middleware(
) )
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
@app.get('/') @app.get('/')
async def receive_url(url: Optional[str] = None): async def receive_url(url: Optional[str] = None):
if url is None: if url is None:
@ -42,9 +25,7 @@ async def receive_url(url: Optional[str] = None):
domain = urlparse(url).netloc domain = urlparse(url).netloc
if domain not in SHORTEN_DOMAINS: if domain not in UNSHORTENERS:
return {"error": f"cannot shorten {url}"} return {"error": f"cannot unshorten {domain}"}
else:
unshortened = unshorten_url(url) return UNSHORTENERS[domain](url)
return {"result": unshortened}

17
server/src/unshorten.py Normal file
View File

@ -0,0 +1,17 @@
import re
import requests
def unshorten_twitter(url):
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