all repos — FixYouTube-legacy @ f3d2077af5474ab76e6286695a0c6e8880073d57

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    formats = map(handle_format, info["formats"])
33    formats = filter(lambda x: x is not None, formats)
34    try:
35        max_format = max(formats, key=lambda x:x["quality"])
36    except ValueError:
37        return None
38
39    return {
40        "id": info["id"],
41        "title": info["title"],
42        "description": truncate_lines(info["description"]),
43        "uploader": info["uploader"],
44        "uploader_id": info["uploader_id"],
45        "video_ext": max_format["video_ext"],
46        "height": max_format["height"],
47        "width": max_format["width"],
48        "url": max_format["url"],
49    }