all repos — FixYouTube-legacy @ 5e703053115a838fbc8984de5e6c4cbffe526ba5

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
 4import logging
 5logger = logging.getLogger(__name__)
 6
 7def get_url(video: str):
 8    req_url = c.INVIDIOUS_ENDPOINT.format(instance=c.INVIDIOUS_INSTANCE, video=video)
 9    logger.debug("GET: " + req_url)
10    return req_url
11
12def get_info_from_api(video):
13    try:
14        res = get(get_url(video))
15    except Exception as e:
16        logger.warn("GET error: " + str(e))
17        c.new_instance()
18        return get_info_from_api(video)
19    
20    try:
21        parsed = res.json()
22    except JSONDecodeError:
23        logger.warn("JSON decode failed for the following video: " + video)
24        return None
25    
26    try:
27        format = [ x for x in parsed["formatStreams"] if x["container"] == "mp4" ][-1]
28    except KeyError:
29        return None
30    
31    width, height = format["size"].split("x")
32
33    return {
34        "videoId": parsed["videoId"],
35        "title": parsed["title"],
36        "description": parsed["description"],
37        "uploader": parsed["author"],
38        "duration": parsed["lengthSeconds"],
39        "height": height,
40        "width": width,
41        "url": format["url"]
42    }