added link

This commit is contained in:
garickbadalov 2023-08-14 17:47:15 +03:00
parent 7331ef166c
commit 71c860689a
3 changed files with 42 additions and 12 deletions

View File

@ -1,6 +1,8 @@
import os
from fastapi import APIRouter, Form, HTTPException from fastapi import APIRouter, Form, HTTPException
from starlette.requests import Request from starlette.requests import Request
from starlette.responses import HTMLResponse from starlette.responses import HTMLResponse, FileResponse
from starlette.templating import Jinja2Templates from starlette.templating import Jinja2Templates
from src.core.ydl import VideoDownloader from src.core.ydl import VideoDownloader
@ -18,17 +20,30 @@ async def index(request: Request):
@main_router.post('/submit') @main_router.post('/submit')
def disable_cat(request: Request, link: str = Form(...)): async def get_url_for_download_video(request: Request, link: str = Form(...)):
downloader = VideoDownloader(link=link, ydl_opts={ file_name = VideoDownloader.get_unique_video_filename()
ydl_opts = {
"forceurl": True, "forceurl": True,
"username": "garick.badalov@yandex.ru", 'outtmpl': f'downloads/%(extractor_key)s/{file_name}.%(ext)s'
"password": "garik876.", # "username": "garick.badalov@yandex.ru",
}) # "password": "garik876.",
}
downloader = VideoDownloader(link=link, ydl_opts=ydl_opts)
try: try:
result = downloader.download() result = downloader.download()
file_path = str(request.base_url) + f"{file_name}.mp4"
except SiteNotImplementedException as ex: except SiteNotImplementedException as ex:
raise HTTPException( raise HTTPException(
status_code=400, status_code=400,
detail=ex.message detail=ex.message
) )
return templates.TemplateResponse("index.html", {"request": request, "result": result["url"]}) return templates.TemplateResponse("index.html", {"request": request, "result": file_path})
@main_router.get('/{file_path}', response_class=FileResponse)
async def download_video(request: Request, file_path):
base = os.path.dirname(os.path.dirname(os.path.abspath(file_path)))
BASE_DOWNLOAD_DIR = os.path.join(base, "src", "downloads")
BASE_YOUTUBE_DIR = os.path.join(BASE_DOWNLOAD_DIR, "Youtube")
return BASE_YOUTUBE_DIR + f'/{file_path}'

View File

@ -1,4 +1,8 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import os
import uuid
from datetime import datetime
from urllib.parse import urlparse from urllib.parse import urlparse
import youtube_dl import youtube_dl
@ -7,15 +11,25 @@ from src.exceptions.download_exceptions import SiteNotImplementedException
class VideoDownloader: class VideoDownloader:
SUPPORTING_WEBSITES = [
"ok.ru", "vk.com", "www.youtube.com"
]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DOWNLOAD_DIR = os.path.join(BASE_DIR, "downloads")
BASE_YOUTUBE_DIR = os.path.join(BASE_DOWNLOAD_DIR, "Youtube")
def __init__(self, link: str, ydl_opts: dict = None, username: str = None, password: str = None): def __init__(self, link: str, ydl_opts: dict = None, username: str = None, password: str = None):
self.link = link self.link = link
self.ydl_opts = ydl_opts self.ydl_opts = ydl_opts
self.username = username self.username = username
self.password = password self.password = password
self.SUPPORTING_WEBSITES = [ @staticmethod
"ok.ru", "vk.com", "www.youtube.com" def get_unique_video_filename():
] prefix = f'vid_{datetime.now().strftime("%Y%m%d%H%M%S")}'
random_uuid4 = uuid.uuid4().hex[:8]
filename = f"{prefix}_{random_uuid4}"
return filename
def download(self): def download(self):
domain = urlparse(self.link).netloc domain = urlparse(self.link).netloc
@ -25,5 +39,4 @@ class VideoDownloader:
with youtube_dl.YoutubeDL(self.ydl_opts if self.ydl_opts else {}) as ydl: with youtube_dl.YoutubeDL(self.ydl_opts if self.ydl_opts else {}) as ydl:
ydl.download([self.link]) ydl.download([self.link])
result = ydl.extract_info(self.link, download=False) result = ydl.extract_info(self.link, download=False)
url = result['formats'][-1] return result
return url

View File

@ -13,5 +13,7 @@ app.include_router(
main_router, main_router,
) )
app.mount("/downloads", StaticFiles(directory="downloads"), name="downloads")
if __name__ == '__main__': if __name__ == '__main__':
uvicorn.run("src.main:app", host="localhost", log_level="info") uvicorn.run("src.main:app", host="localhost", log_level="info")