all repos — FixYouTube-legacy @ bc789d7b3a387f7bfb8a1507ccf16cc97453c70c

A better way to embed YouTube videos everywhere (inspired by FixTweet).

fixyoutube/api.py (view raw)

 1from requests import get
 2from requests.exceptions import JSONDecodeError
 3import fixyoutube.constants as c
 4
 5def get_url(video: str):
 6    return c.INVIDIOUS_ENDPOINT.format(instance=c.INVIDIOUS_INSTANCE, video=video)
 7
 8def get_info_from_api(video):
 9    try:
10        res = get(get_url(video))
11    except Exception:
12        print("Bad instance.")
13        c.new_instance()
14        return get_info_from_api(video)
15    
16    try:
17        parsed = res.json()
18    except JSONDecodeError:
19        print("JSON decode error. Bad instance or video does not exist.")
20        return None
21    
22    try:
23        format = [ x for x in parsed["formatStreams"] if x["container"] == "mp4"][-1]
24    except KeyError:
25        return None
26    
27    width, height = format["size"].split("x")
28
29    return {
30        "videoId": parsed["videoId"],
31        "title": parsed["title"],
32        "description": parsed["description"],
33        "uploader": parsed["author"],
34        "duration": parsed["lengthSeconds"],
35        "height": height,
36        "width": width,
37        "url": format["url"]
38    }