import yt_dlp import tempfile import os def download_video(url: str, cookie: str = None, video_id: str = "video") -> str: output_path = f"/tmp/{video_id}.mp4" ydl_opts = { "format": "best[ext=mp4]/best", "outtmpl": output_path, "quiet": False, "noplaylist": True, "no_cache_dir": True, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", } cookie_file = None if cookie: # Convert raw cookie string to Netscape format try: cookie_file = tempfile.NamedTemporaryFile(delete=False, mode="w", suffix=".txt") cookie_file.write("# Netscape HTTP Cookie File\n") for pair in cookie.split(";"): parts = pair.strip().split("=") if len(parts) == 2: name, value = parts cookie_file.write(f".youtube.com\tTRUE\t/\tFALSE\t2145916800\t{name}\t{value}\n") cookie_file.close() ydl_opts["cookiefile"] = cookie_file.name except Exception as e: print("๐Ÿ”ฅ Failed to process cookies:", str(e)) try: print(f"๐Ÿ“ฅ Downloading video from {url} to {output_path}") with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) if not os.path.exists(output_path): raise RuntimeError("Download finished but output file not found.") return output_path except Exception as e: print("๐Ÿ”ฅ Download failed:", str(e)) raise finally: if cookie_file and os.path.exists(cookie_file.name): os.remove(cookie_file.name) print("๐Ÿงน Temporary cookie file removed.")