all repos — FixYouTube-legacy @ 942e0d577869657273327c2480cf05eb5b6758f7

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 = { k: truncate_lines(info[k]) for k in ["id", "title", "description", "uploader", "duration"] }
36    yt_info.update({ "height": 0, "width": 0, "url": None })
37
38    formats = map(handle_format, info["formats"])
39    formats = filter(lambda x: x is not None, formats)
40    try:
41        max_format = max(formats, key=lambda x:x["quality"])
42        yt_info.update({ k: max_format[k] for k in ["height", "width", "url"] })
43    except ValueError:
44        pass
45    finally:
46        return yt_info