2021-02-07 17:46:20 +13:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
import json
|
2021-02-07 17:46:20 +13:00
|
|
|
import re
|
2021-02-25 23:40:08 +13:00
|
|
|
from typing import Optional
|
2021-02-06 21:35:50 +13:00
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
from bs4 import BeautifulSoup
|
2021-02-11 12:10:40 +13:00
|
|
|
from praw.models import Submission
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-04-12 19:58:32 +12:00
|
|
|
from bdfr.exceptions import SiteDownloaderError
|
|
|
|
from bdfr.resource import Resource
|
|
|
|
from bdfr.site_authenticator import SiteAuthenticator
|
2021-04-28 20:50:18 +12:00
|
|
|
from bdfr.site_downloaders.redgifs import Redgifs
|
2021-02-06 21:35:50 +13:00
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-04-28 20:50:18 +12:00
|
|
|
class Gfycat(Redgifs):
|
2021-02-15 18:12:27 +13:00
|
|
|
def __init__(self, post: Submission):
|
|
|
|
super().__init__(post)
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2021-02-26 21:57:05 +13:00
|
|
|
def find_resources(self, authenticator: Optional[SiteAuthenticator] = None) -> list[Resource]:
|
2021-02-25 23:40:08 +13:00
|
|
|
return super().find_resources(authenticator)
|
2020-05-29 06:42:11 +12:00
|
|
|
|
|
|
|
@staticmethod
|
2022-02-18 15:49:46 +13:00
|
|
|
def _get_link(url: str) -> set[str]:
|
2022-12-03 18:11:17 +13:00
|
|
|
gfycat_id = re.match(r".*/(.*?)/?$", url).group(1)
|
|
|
|
url = "https://gfycat.com/" + gfycat_id
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-04-06 12:48:21 +12:00
|
|
|
response = Gfycat.retrieve_url(url)
|
2022-12-03 18:11:17 +13:00
|
|
|
if re.search(r"(redgifs|gifdeliverynetwork)", response.url):
|
2021-05-16 14:16:47 +12:00
|
|
|
url = url.lower() # Fixes error with old gfycat/redgifs links
|
2021-04-28 20:50:18 +12:00
|
|
|
return Redgifs._get_link(url)
|
2021-03-21 23:31:18 +13:00
|
|
|
|
2022-12-03 18:11:17 +13:00
|
|
|
soup = BeautifulSoup(response.text, "html.parser")
|
|
|
|
content = soup.find("script", attrs={"data-react-helmet": "true", "type": "application/ld+json"})
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-04-06 13:04:08 +12:00
|
|
|
try:
|
2022-12-03 18:11:17 +13:00
|
|
|
out = json.loads(content.contents[0])["video"]["contentUrl"]
|
2021-04-28 17:17:21 +12:00
|
|
|
except (IndexError, KeyError, AttributeError) as e:
|
2022-12-03 18:11:17 +13:00
|
|
|
raise SiteDownloaderError(f"Failed to download Gfycat link {url}: {e}")
|
2021-04-06 13:04:08 +12:00
|
|
|
except json.JSONDecodeError as e:
|
2022-12-03 18:11:17 +13:00
|
|
|
raise SiteDownloaderError(f"Did not receive valid JSON data: {e}")
|
|
|
|
return {
|
|
|
|
out,
|
|
|
|
}
|