1
0
Fork 0
mirror of synced 2024-05-17 10:42:39 +12:00
bulk-downloader-for-reddit/bdfr/site_downloaders/redgifs.py

62 lines
2.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
import json
2021-03-20 01:28:41 +13:00
import re
2022-09-01 13:19:07 +12:00
import urllib.parse
2021-02-25 23:40:08 +13:00
from typing import Optional
2021-02-11 12:10:40 +13:00
from praw.models import Submission
2021-04-23 23:06:16 +12:00
from bdfr.exceptions import SiteDownloaderError
2021-04-12 19:58:32 +12:00
from bdfr.resource import Resource
from bdfr.site_authenticator import SiteAuthenticator
2021-04-28 20:50:18 +12:00
from bdfr.site_downloaders.base_downloader import BaseDownloader
2021-04-28 20:50:18 +12:00
class Redgifs(BaseDownloader):
2021-02-15 18:12:27 +13:00
def __init__(self, post: Submission):
super().__init__(post)
2021-02-26 21:57:05 +13:00
def find_resources(self, authenticator: Optional[SiteAuthenticator] = None) -> list[Resource]:
media_urls = self._get_link(self.post.url)
return [Resource(self.post, m, Resource.retry_download(m), None) for m in media_urls]
@staticmethod
def _get_link(url: str) -> set[str]:
try:
redgif_id = re.match(r'.*/(.*?)(\..{0,})?$', url).group(1)
except AttributeError:
raise SiteDownloaderError(f'Could not extract Redgifs ID from {url}')
content = Redgifs.retrieve_url(f'https://api.redgifs.com/v2/gifs/{redgif_id}')
if content is None:
raise SiteDownloaderError('Could not read the page source')
try:
response_json = json.loads(content.text)
except json.JSONDecodeError as e:
raise SiteDownloaderError(f'Received data was not valid JSON: {e}')
out = set()
try:
if response_json['gif']['type'] == 1: # type 1 is a video
out.add(response_json['gif']['urls']['hd'])
elif response_json['gif']['type'] == 2: # type 2 is an image
if response_json['gif']['gallery']:
content = Redgifs.retrieve_url(
2022-09-17 06:47:55 +12:00
f'https://api.redgifs.com/v2/gallery/{response_json["gif"]["gallery"]}')
response_json = json.loads(content.text)
out = {p['urls']['hd'] for p in response_json['gifs']}
else:
out.add(response_json['gif']['urls']['hd'])
else:
raise KeyError
except (KeyError, AttributeError):
raise SiteDownloaderError('Failed to find JSON data in page')
# Update subdomain if old one is returned
out = {re.sub('thumbs2', 'thumbs3', link) for link in out}
out = {re.sub('thumbs3', 'thumbs4', link) for link in out}
2021-03-20 01:28:41 +13:00
return out