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