Files
mateusz/bot/utils/helpers.py
T
2026-04-22 20:19:15 +02:00

78 lines
2.6 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)
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)
url_hash = hashlib.sha1(yt_url.encode()).hexdigest()[:10]
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 {filename} ({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,
'url': yt_url,
}