import os import sys from datetime import datetime from pathlib import Path from typing import Dict import ffmpeg from discord_webhook import DiscordWebhook from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse from discord_embed.settings import Settings app = FastAPI( title="discord-nice-embed", description=Settings.description, version="0.0.1", contact={ "name": "Joakim Hellsén", "url": "https://github.com/TheLovinator1", "email": "tlovinator@gmail.com", }, license_info={ "name": "GPL-3.0", "url": "https://www.gnu.org/licenses/gpl-3.0.txt", }, ) async def send_webhook(message: str) -> None: """Send webhook to Discord. Args: message (str): The message to send. """ webhook = DiscordWebhook( url=Settings.webhook_url, content=message, rate_limit_retry=True, ) await webhook.execute() async def video_file_uploaded(file: UploadFile) -> Dict[str, str]: """Save video to disk, generate HTML, thumbnail, and return a .html URL. Args: file (UploadFile): Our file object. Returns: Dict[str, str]: Returns URL for video. """ # Create folder if it doesn't exist. folder_video = os.path.join(Settings.upload_folder, "video") Path(folder_video).mkdir(parents=True, exist_ok=True) # Replace spaces with dots in filename. filename = file.filename.replace(" ", ".") # Save file to disk. file_location = os.path.join(folder_video, filename) with open(file_location, "wb+") as file: await file.write(file.file.read()) file_url = f"{Settings.domain}/video/{filename}" height, width = find_video_resolution(file_location) screenshot_url = make_thumbnail_from_video(file_location, filename) html_url = generate_html_for_videos( url=file_url, width=width, height=height, screenshot=screenshot_url, filename=filename, ) await send_webhook(f"{Settings.domain}/{filename} was uploaded.") return {"html_url": f"{html_url}"} @app.post("/uploadfiles/") async def upload_file(file: UploadFile = File(...)) -> Dict[str, str]: """Page for uploading files. If it is a video, we need to make a HTML file, and a thumbnail otherwise we can just save the file and return the URL for it. If something goes wrong, we will send a message to Discord. Args: file (UploadFile): Our uploaded file. Returns: Dict[str, str]: Returns a dict with the filename or a link to the .html if it was a video. """ try: if file.content_type.startswith("video/"): return video_file_uploaded(file) with open(f"{Settings.upload_folder}/{file.filename}", "wb+") as file: await file.write(file.file.read()) domain_url = f"{Settings.domain}/{file.filename}" await send_webhook(f"{domain_url} was uploaded.") return {"html_url": domain_url} except Exception as e: await send_webhook(f"Something went wrong for {domain_url}:\n{e}") return {"error": f"Something went wrong: {e}"} @app.get("/", response_class=HTMLResponse) async def main(): """Our index view. You can upload files here. Returns: HTMLResponse: Returns HTML for site. """ return """