"""Website for uploading files and creating .HTMLs and thumbnails so we can embed files in Discord. """ import os import sys from datetime import datetime from pathlib import Path import ffmpeg from dotenv import load_dotenv from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse load_dotenv() app = FastAPI( title="discord-nice-embed", description=""" Discord will only create embeds for videos and images if they are smaller than 8mb. We can "abuse" this by using the "twitter:image" HTML meta tag. """, 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", }, ) # Check if user has added a domain to the environment. try: domain = os.environ["DOMAIN"] except KeyError: sys.exit("discord-embed: Environment variable 'DOMAIN' is missing!") # We check if the domain ends with a forward slash. If it does, we remove it. if domain.endswith("/"): domain = domain[:-1] # Check if we have a folder for uploads. try: upload_folder = os.environ["UPLOAD_FOLDER"] except KeyError: sys.exit("discord-embed: Environment variable 'UPLOAD_FOLDER' is missing!") # We check if the upload folder ends with a forward slash. If it does, we remove it. if upload_folder.endswith("/"): upload_folder = upload_folder[:-1] @app.post("/uploadfiles/") async def upload_file(file: UploadFile = File(...)): """Page for uploading files. Args: file (UploadFile): Our uploaded file. Defaults to File(...). Returns: HTMLResponse: Returns HTML for site. """ # TODO: Add syntax highlighting for text. # Make custom html for video files. if file.content_type.startswith("video/"): # Create folder if it doesn't exist. Path(f"{upload_folder}/video").mkdir(parents=True, exist_ok=True) # Save file to disk. with open(f"{upload_folder}/video/{file.filename}", "wb+") as file_object: file_object.write(file.file.read()) file_url = f"{domain}/video/{file.filename}" file_location = f"{upload_folder}/video/{file.filename}" height, width = find_video_resolution(file_location) screenshot_url = make_thumbnail_from_video(file_location, file.filename) html_url = generate_html( filename=file.filename, url=file_url, width=width, height=height, screenshot=screenshot_url ) return {"html_url": f"{html_url}"} # Save file to disk. with open(f"{upload_folder}/{file.filename}", "wb+") as file_object: file_object.write(file.file.read()) return {"html_url": f"{domain}/{file.filename}"} @app.get("/", response_class=HTMLResponse) async def main(): """Our index view. You can upload files here. Returns: HTMLResponse: Returns HTML for site. """ return """