all repos — FixYouTube-legacy @ 094043cf7ddb5d4defea2dfb10e77d75f6a04df0

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