File size: 1,785 Bytes
c4ae7d1
 
 
 
caaf68f
 
c4ae7d1
 
 
 
 
 
f89c84a
 
c4ae7d1
 
caaf68f
 
c4ae7d1
caaf68f
 
 
 
 
 
 
 
 
 
 
 
 
a11e902
 
da459e3
c4ae7d1
 
 
 
 
 
 
 
 
 
 
 
caaf68f
 
da459e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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.")