import os from fastapi import APIRouter, Form, HTTPException from starlette.requests import Request from fastapi.responses import JSONResponse from starlette.responses import HTMLResponse, FileResponse from starlette.templating import Jinja2Templates from src.core.ydl import VideoDownloader from src.exceptions.download_exceptions import SiteNotImplementedException main_router = APIRouter() templates = Jinja2Templates(directory="templates") @main_router.get("/", response_class=HTMLResponse) async def index(request: Request): return templates.TemplateResponse("index.html", {"request": request}) @main_router.post('/submit') async def get_url_for_download_video(request: Request, link: str = Form(...)): file_name = VideoDownloader.get_unique_video_filename() ydl_opts = { "forceurl": True, 'outtmpl': f'downloads/%(extractor_key)s/{file_name}.%(ext)s' } downloader = VideoDownloader(link=link, ydl_opts=ydl_opts) try: result = downloader.download() link_to_download_video = str(request.base_url) + f"{file_name}.{result['formats'][-1]['ext']}" except SiteNotImplementedException as ex: raise HTTPException( status_code=400, detail=ex.message ) return JSONResponse({"result": link_to_download_video}) @main_router.get('/{file_path}', response_class=FileResponse) async def download_video(file_path): base = os.path.dirname(os.path.dirname(os.path.abspath(file_path))) base_download_dir = os.path.join(base, "src", "downloads") youtube_dir = os.path.join(base_download_dir, "Youtube") return FileResponse(youtube_dir + f'/{file_path}', media_type="multipart/form-data")