Refactor video file upload process to remove illegal characters and streamline file handling

This commit is contained in:
2025-02-20 22:44:43 +01:00
parent b4ec21a7e4
commit 64074efb69

View File

@ -1,12 +1,12 @@
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
from discord_embed import settings
from discord_embed.generate_html import generate_html_for_videos
from discord_embed.main import remove_illegal_chars
from discord_embed.video import Resolution, make_thumbnail, video_resolution
if TYPE_CHECKING:
@ -15,22 +15,8 @@ if TYPE_CHECKING:
logger: logging.Logger = logging.getLogger("uvicorn.error")
@dataclass
class VideoFile:
"""A video file.
filename: The filename of the video file.
location: The location of the video file.
"""
filename: str
location: str
def save_to_disk(file: UploadFile) -> VideoFile:
"""Save the uploaded file to disk.
If spaces in the filename, replace with dots.
def do_things(file: UploadFile) -> str:
"""Save video to disk, generate HTML, thumbnail, and return a .html URL.
Args:
file: Our uploaded file.
@ -39,7 +25,7 @@ def save_to_disk(file: UploadFile) -> VideoFile:
ValueError: If the filename is None.
Returns:
VideoFile object with the filename and location.
Returns URL for video.
"""
if file.filename is None:
msg = "Filename is None"
@ -49,37 +35,28 @@ def save_to_disk(file: UploadFile) -> VideoFile:
save_folder_video = Path(settings.upload_folder, "video")
Path(save_folder_video).mkdir(parents=True, exist_ok=True)
# Replace spaces with dots in the filename.
# Replace spaces with dots and remove illegal characters
filename: str = file.filename.replace(" ", ".")
filename = remove_illegal_chars(filename)
filename = filename.strip()
# Save the uploaded file to disk.
file_location = Path(save_folder_video, filename)
with Path.open(file_location, "wb+") as f:
f.write(file.file.read())
return VideoFile(filename, str(file_location))
def do_things(file: UploadFile) -> str:
"""Save video to disk, generate HTML, thumbnail, and return a .html URL.
Args:
file: Our uploaded file.
Returns:
Returns URL for video.
"""
video_file: VideoFile = save_to_disk(file)
file_url: str = f"{settings.serve_domain}/video/{video_file.filename}"
res: Resolution = video_resolution(video_file.location)
screenshot_url: str = make_thumbnail(video_file.location, video_file.filename)
file_url: str = f"{settings.serve_domain}/video/{filename}"
res: Resolution = video_resolution(str(file_location))
screenshot_url: str = make_thumbnail(str(file_location), filename)
html_url: str = generate_html_for_videos(
url=file_url,
width=res.width,
height=res.height,
screenshot=screenshot_url,
filename=video_file.filename,
filename=filename,
)
logger.info("Generated HTML URL: %s", html_url)
logger.debug("Video file location: %s", str(file_location))
logger.debug("Video filename: %s", filename)
return html_url