all repos — FixYouTube-legacy @ d7855fbe2c2ad5d51358e6e79b985f2b27989e7f

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    try:
18        if format["filesize"] > c.MAX_SIZE_BYTES:
19            return None # too large
20    except TypeError:
21        return None
22
23    return format
24
25def get_info_ytdl(yt_id: str):
26    info = ydl.extract_info(c.BASE_URL + yt_id, download=False)
27    formats = map(handle_format, info["formats"])
28    formats = filter(lambda x: x is not None, formats)
29    try:
30        max_format = max(formats, key=lambda x:x["quality"])
31    except ValueError:
32        return None
33    
34    return {
35        "id": info["id"],
36        "title": info["title"],
37        "description": info["description"],
38        "uploader": info["uploader"],
39        "uploader_id": info["uploader_id"],
40        "video_ext": max_format["video_ext"],
41        "height": max_format["height"],
42        "width": max_format["width"],
43        "url": max_format["url"],
44    }