89 lines
2.9 KiB
Python
89 lines
2.9 KiB
Python
import os
|
|
import yt_dlp
|
|
import hashlib
|
|
|
|
|
|
def rotate_downloads(downloads_dir: str):
|
|
MAX_FILES = os.getenv('MAX_FILES')
|
|
if not MAX_FILES.isnumeric():
|
|
return {'status': 'error', 'message': f'MAX_FILES: \"{MAX_FILES}\" - nie jest cyfrą.'}
|
|
|
|
MAX_FILES = int(MAX_FILES)
|
|
files = [
|
|
os.path.join(downloads_dir, f)
|
|
for f in os.listdir(downloads_dir)
|
|
if os.path.isfile(os.path.join(downloads_dir, f))
|
|
]
|
|
|
|
if len(files) >= MAX_FILES:
|
|
files.sort(key=os.path.getmtime)
|
|
to_delete = files[:len(files) - MAX_FILES + 1]
|
|
for f in to_delete:
|
|
os.remove(f)
|
|
print(f'Usunięto stary plik: \"{os.path.basename(f)}\"')
|
|
|
|
|
|
def download_video(yt_url: str) -> dict:
|
|
MAX_DUR = os.getenv('MAX_DURATION')
|
|
if not MAX_DUR.isnumeric():
|
|
return {'status': 'error', 'message': f'MAX_DUR: "{MAX_DUR}" - nie jest cyfrą.'}
|
|
|
|
MAX_DUR = int(MAX_DUR)
|
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
DOWNLOADS = os.path.join(BASE_DIR, 'downloads')
|
|
os.makedirs(DOWNLOADS, exist_ok=True)
|
|
url_hash = hashlib.sha1(yt_url.encode()).hexdigest()[:10]
|
|
|
|
existing = [f for f in os.listdir(DOWNLOADS) if url_hash in f]
|
|
if existing:
|
|
print(f'Znaleziono plik "{existing[0]}" ({yt_url})')
|
|
return {
|
|
'status': 'success',
|
|
'filename': os.path.join(DOWNLOADS, existing[0]),
|
|
'title': {existing[0]},
|
|
'cached': True,
|
|
}
|
|
|
|
with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
|
|
try:
|
|
print(f'Pobieranie "{yt_url}"')
|
|
info = ydl.extract_info(yt_url, download=False)
|
|
except Exception as e:
|
|
print(f'Nie można pobrać metadanych: {e}')
|
|
return {'status': 'error', 'message': f'Nie można pobrać metadanych: {e}'}
|
|
|
|
duration = info.get('duration', 0)
|
|
if duration > MAX_DUR:
|
|
print(f'Wideo jest za długie ({duration // 60}m {duration % 60}s). Maksymalnie {MAX_DUR // 60}m {MAX_DUR % 60}s.')
|
|
return {
|
|
'status': 'error',
|
|
'message': f'Wideo jest za długie ({duration // 60}m {duration % 60}s). Maksymalnie {MAX_DUR // 60}m {MAX_DUR % 60}s.'
|
|
}
|
|
|
|
rotate_downloads(DOWNLOADS)
|
|
|
|
ydl_opts = {
|
|
'format': 'bestvideo+bestaudio/best',
|
|
'merge_output_format': 'mp4',
|
|
'outtmpl': os.path.join(DOWNLOADS, f'%(title)s_{url_hash}.%(ext)s'),
|
|
'quiet': True,
|
|
}
|
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
try:
|
|
info = ydl.extract_info(yt_url, download=True)
|
|
filename = ydl.prepare_filename(info)
|
|
print(f'Pobrano "{info.get("title")}" ({yt_url})')
|
|
except Exception as e:
|
|
print(f'Błąd pobierania: {e}')
|
|
return {'status': 'error', 'message': f'Błąd pobierania: {e}'}
|
|
|
|
return {
|
|
'status': 'success',
|
|
'filename': filename,
|
|
'title': info.get('title'),
|
|
'duration': duration,
|
|
'cached': False,
|
|
'url': yt_url,
|
|
}
|