Rotation and hashing V1.0.1

This commit is contained in:
Patryk Mazur
2026-04-22 19:36:56 +02:00
parent 474793bcaa
commit 1514ce1dc6
4 changed files with 65 additions and 16 deletions
+51 -7
View File
@@ -1,20 +1,64 @@
import os
import yt_dlp
import hashlib
def download_video(yt_url: str) -> str:
def rotate_downloads(downloads_dir: str):
MAX_FILES = os.getenv('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')
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DOWNLOADS = os.path.join(BASE_DIR, "downloads")
DOWNLOADS = os.path.join(BASE_DIR, 'downloads')
os.makedirs(DOWNLOADS, exist_ok=True)
with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
try:
info = ydl.extract_info(yt_url, download=False)
except Exception as e:
return {'status': 'error', 'message': f'Nie można pobrać metadanych: {e}'}
duration = info.get('duration', 0)
if duration > MAX_DUR:
return {
'status': 'error',
'message': f'Wideo jest za długie ({duration // 60}m {duration % 60}s). Maksymalnie 10 minut.'
}
url_hash = hashlib.md5(yt_url.encode()).hexdigest()[:10]
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'merge_output_format': 'mp4',
'outtmpl': f'{DOWNLOADS}/%(title)s.%(ext)s',
'outtmpl': os.path.join(DOWNLOADS, f'%(title)s_{url_hash}.%(ext)s'),
'quiet': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
os.makedirs(DOWNLOADS, exist_ok=True)
info = ydl.extract_info(yt_url, download=True)
filename = ydl.prepare_filename(info)
try:
info = ydl.extract_info(yt_url, download=True)
filename = ydl.prepare_filename(info)
except Exception as e:
return {'status': 'error', 'message': f'Błąd pobierania: {e}'}
return filename
return {
'status': 'success',
'filename': filename,
'title': info.get('title'),
'duration': duration,
'url': yt_url,
}