Add type hints

This commit is contained in:
2023-01-09 04:25:20 +01:00
parent fc424f7263
commit ab477c0ab4
10 changed files with 69 additions and 64 deletions

View File

@ -18,7 +18,7 @@ def generate_html_for_videos(url: str, width: int, height: int, screenshot: str,
Returns:
Returns HTML for video.
"""
video_html = f"""
video_html: str = f"""
<!DOCTYPE html>
<html>
<!-- Generated at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} -->
@ -33,13 +33,13 @@ def generate_html_for_videos(url: str, width: int, height: int, screenshot: str,
</head>
</html>
"""
domain = settings.serve_domain
domain: str = settings.serve_domain
html_url: str = urljoin(domain, filename)
# Take the filename and append .html to it.
filename += ".html"
file_path = os.path.join(settings.upload_folder, filename)
file_path: str = os.path.join(settings.upload_folder, filename)
with open(file_path, "w", encoding="utf-8") as f:
f.write(video_html)

View File

@ -10,7 +10,7 @@ from discord_embed import settings
from discord_embed.video_file_upload import do_things
from discord_embed.webhook import send_webhook
app = FastAPI(
app: FastAPI = FastAPI(
title="discord-nice-embed",
description=settings.DESCRIPTION,
version="0.0.1",
@ -26,7 +26,7 @@ app = FastAPI(
)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
templates: Jinja2Templates = Jinja2Templates(directory="templates")
@app.post("/uploadfiles/")
@ -46,12 +46,12 @@ async def upload_file(file: UploadFile = File(...)) -> Dict[str, str]:
if file.content_type.startswith("video/"):
return await do_things(file)
filename = await remove_illegal_chars(file.filename)
filename: str = await remove_illegal_chars(file.filename)
with open(f"{settings.upload_folder}/{filename}", "wb+") as f:
f.write(file.file.read())
domain_url = urljoin(settings.serve_domain, filename)
domain_url: str = urljoin(settings.serve_domain, filename)
send_webhook(f"{domain_url} was uploaded.")
return {"html_url": domain_url}
@ -66,8 +66,8 @@ async def remove_illegal_chars(filename: str) -> str:
Returns a string with the filename without illegal characters.
"""
filename = filename.replace(" ", ".")
illegal_characters = [
filename: str = filename.replace(" ", ".") # type: ignore
illegal_characters: list[str] = [
"*",
'"',
"<",
@ -91,7 +91,8 @@ async def remove_illegal_chars(filename: str) -> str:
",",
]
for character in illegal_characters:
filename = filename.replace(character, "")
filename: str = filename.replace(character, "") # type: ignore
return filename
@ -102,7 +103,7 @@ async def main(request: Request):
You can upload files here.
Returns:
HTMLResponse: Returns HTML for site.
TemplateResponse: Returns HTML for site.
"""
return templates.TemplateResponse("index.html", {"request": request})

View File

@ -4,7 +4,7 @@ import sys
from dotenv import load_dotenv
DESCRIPTION = (
DESCRIPTION: str = (
"Discord will only create embeds for videos and images if they are "
"smaller than 8 mb. We can 'abuse' this by creating a .html that "
"contains the 'twitter:player' HTML meta tag linking to the video."
@ -14,7 +14,7 @@ load_dotenv()
# Check if user has added a domain to the environment.
try:
serve_domain = os.environ["SERVE_DOMAIN"]
serve_domain: str = os.environ["SERVE_DOMAIN"]
except KeyError:
sys.exit("discord-embed: Environment variable 'SERVE_DOMAIN' is missing!")
@ -24,7 +24,7 @@ if serve_domain.endswith("/"):
# Check if we have a folder for uploads.
try:
upload_folder = os.environ["UPLOAD_FOLDER"]
upload_folder: str = os.environ["UPLOAD_FOLDER"]
except KeyError:
sys.exit("Environment variable 'UPLOAD_FOLDER' is missing!")
@ -37,6 +37,6 @@ if upload_folder.endswith("/"):
# Discord webhook URL
try:
webhook_url = os.environ["WEBHOOK_URL"]
webhook_url: str = os.environ["WEBHOOK_URL"]
except KeyError:
sys.exit("Environment variable 'WEBHOOK_URL' is missing!")

View File

@ -33,8 +33,8 @@ def video_resolution(path_to_video: str) -> Resolution:
print("No video stream found", file=sys.stderr)
sys.exit(1)
width = int(video_stream["width"])
height = int(video_stream["height"])
width: int = int(video_stream["width"])
height: int = int(video_stream["height"])
return Resolution(height, width)

View File

@ -35,14 +35,14 @@ def save_to_disk(file: UploadFile) -> VideoFile:
VideoFile object with the filename and location.
"""
# Create the folder where we should save the files
folder_video = os.path.join(settings.upload_folder, "video")
folder_video: str = os.path.join(settings.upload_folder, "video")
Path(folder_video).mkdir(parents=True, exist_ok=True)
# Replace spaces with dots in the filename.
filename = file.filename.replace(" ", ".")
filename: str = file.filename.replace(" ", ".")
# Save the uploaded file to disk.
file_location = os.path.join(folder_video, filename)
file_location: str = os.path.join(folder_video, filename)
with open(file_location, "wb+") as f:
f.write(file.file.read())
@ -61,10 +61,10 @@ async def do_things(file: UploadFile) -> Dict[str, str]:
video_file: VideoFile = save_to_disk(file)
file_url = f"{settings.serve_domain}/video/{video_file.filename}"
file_url: str = f"{settings.serve_domain}/video/{video_file.filename}"
res: Resolution = video_resolution(video_file.location)
screenshot_url = make_thumbnail(video_file.location, video_file.filename)
html_url = generate_html_for_videos(
screenshot_url: str = make_thumbnail(video_file.location, video_file.filename)
html_url: str = generate_html_for_videos(
url=file_url,
width=res.width,
height=res.height,

View File

@ -9,7 +9,7 @@ def send_webhook(message: str) -> None:
Args:
message: The message to send.
"""
webhook = DiscordWebhook(
webhook: DiscordWebhook = DiscordWebhook(
url=settings.webhook_url,
content=message,
rate_limit_retry=True,