all repos — FixYouTube-legacy @ 476e2ef39e5caac3491a4e3f9c4a7d3635d217f4

A better way to embed YouTube videos everywhere (inspired by FixTweet).

fxyoutube/yt_info.py (view raw)

 1from yt_dlp import YoutubeDL
 2import fxyoutube.constants as c
 3ydl = YoutubeDL()
 4
 5def handle_format(format):
 6
 7    if format["resolution"] == "audio only":
 8        return None # audio-only
 9    try:
10        if format["audio_channels"] is None:
11            return None # video-only
12    except KeyError:
13        return None # video-only
14
15    if format["url"].endswith(".m3u8"):
16        return None # HLS stream
17    
18    try:
19        if format["filesize"] > c.MAX_SIZE_BYTES:
20            return None # too large
21    except TypeError:
22        if format["filesize_approx"] > c.MAX_SIZE_BYTES:
23            return None # too large
24
25    return format
26
27def truncate_lines(input_str: str, max: int = 5):
28    return "\n".join(input_str.splitlines()[:5])
29
30def get_info_ytdl(yt_id: str):
31    info = ydl.extract_info(c.BASE_URL + yt_id, download=False)
32
33    yt_info = {
34        "id": info["id"],
35        "title": info["title"],
36        "description": truncate_lines(info["description"]),
37        "uploader": info["uploader"],
38        "uploader_id": info["uploader_id"],
39        "duration": info["duration"],
40    }
41
42    formats = map(handle_format, info["formats"])
43    formats = filter(lambda x: x is not None, formats)
44    try:
45        max_format = max(formats, key=lambda x:x["quality"])
46    except ValueError:
47        yt_info.update({
48            "video_ext": None,
49            "height": 0,
50            "width": 0,
51            "url": None
52        })
53
54    yt_info.update({
55        "video_ext": max_format["video_ext"],
56        "height": max_format["height"],
57        "width": max_format["width"],
58        "url": max_format["url"],
59    })
60
61    return yt_info