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 }
42
43 formats = map(handle_format, info["formats"])
44 formats = filter(lambda x: x is not None, formats)
45 try:
46 max_format = max(formats, key=lambda x:x["quality"])
47 except ValueError:
48 yt_info.update({
49 "height": 0,
50 "width": 0,
51 "url": None
52 })
53 return yt_info
54
55 yt_info.update({
56 "height": max_format["height"],
57 "width": max_format["width"],
58 "url": max_format["url"],
59 })
60
61 return yt_info